package com.tnxst.phexamination.fragment.follow;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.adapter.follow.AddFollowDrugAdapter;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.DoorRecordHypertensionFollowupTwoBinding;
import com.tnxst.phexamination.dto.DiabetesFollowDTO;
import com.tnxst.phexamination.dto.HypertensionFollowDTO;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.fragment.SignFragment;
import com.tnxst.phexamination.public_health_docking_interface.DiabetesInterface;
import com.tnxst.phexamination.public_health_docking_interface.HypertensionInterface;
import com.tnxst.phexamination.public_health_docking_interface.TuberculosisInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;
import com.tnxst.phexamination.vo.DrugVo;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;

import worker8.com.github.radiogroupplus.RadioGroupPlus;

public class HypertensionFollowFragment extends Fragment implements CompoundButton.OnCheckedChangeListener{

    private DoorRecordHypertensionFollowupTwoBinding binding;

    private Context context;

    private GlobalViewModel viewModel;

    private HypertensionFollowDTO hypertensionFollowDTO;

    private List<DrugVo> drug;

    private List<Map<String, Object>> other;

    private List<String> laboratoryString;

    private Map<String, Object> labora;

    private InhabitantDTO inhabitantDTO;

    private AddFollowDrugAdapter addFollowDrugAdapter;

    //新增定位功能及拍照功能的控件
    private EditText address;

    private ImageView picture1;

    private ImageView picture2;

    private ImageView picture3;

    private Switch aSwitch;

    private Button start;

    private TextView del1;

    private TextView del2;

    private TextView del3;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        binding = DataBindingUtil.inflate(inflater, R.layout.door_record_hypertension_followup_two, container, false);
        context = container.getContext();
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        initData();
        initView();
        initAddress();
    }

    private void initAddress() {
        address = binding.include.findViewById(R.id.editTextTextPersonName33);
        picture1 = binding.include.findViewById(R.id.image1);
        picture2 = binding.include.findViewById(R.id.image2);
        picture3 = binding.include.findViewById(R.id.image3);
        aSwitch = binding.include.findViewById(R.id.isFinish);
        start = binding.include.findViewById(R.id.button22);
        del1 = binding.include.findViewById(R.id.text1);
        del2 = binding.include.findViewById(R.id.text2);
        del3 = binding.include.findViewById(R.id.text3);
        viewModel.getAddressUtils().getAddress(address, getActivity());
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureFileUtil.showAlbum(HypertensionFollowFragment.this, PictureConfig.CHOOSE_REQUEST);
            }
        });
        del1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hypertensionFollowDTO.setPicturePath1("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            }
        });
        del2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hypertensionFollowDTO.setPicturePath2("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            }
        });
        del3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hypertensionFollowDTO.setPicturePath3("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);
            }
        });

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    hypertensionFollowDTO.setIsFinish(1);
                else
                    hypertensionFollowDTO.setIsFinish(0);
            }
        });

        if (StringUtils.isNotNull(hypertensionFollowDTO.getPicturePath1()))
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath1(), picture1);
        if (StringUtils.isNotNull(hypertensionFollowDTO.getPicturePath2()))
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath2(), picture2);
        if (StringUtils.isNotNull(hypertensionFollowDTO.getPicturePath3()))
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath3(), picture3);
        if (StringUtils.isNotNull(hypertensionFollowDTO.getAddress())){
            address.setText(hypertensionFollowDTO.getAddress());
        } else{
            viewModel.getAddressUtils().getAddress(address, getActivity());
        }

        if (hypertensionFollowDTO.getIsFinish() == 0)
            aSwitch.setChecked(false);
        else
            aSwitch.setChecked(true);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            hypertensionFollowDTO.setPicturePath1("");
            hypertensionFollowDTO.setPicturePath2("");
            hypertensionFollowDTO.setPicturePath3("");
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);

            List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
            hypertensionFollowDTO.setPicturePath1(selectListPic.size() > 0 ? selectListPic.get(0).getRealPath() : "");
            hypertensionFollowDTO.setPicturePath2(selectListPic.size() > 1 ? selectListPic.get(1).getRealPath() : "");
            hypertensionFollowDTO.setPicturePath3(selectListPic.size() > 2 ? selectListPic.get(2).getRealPath() : "");
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath1(), picture1);
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath2(), picture2);
            Utils.loadChatImage(getActivity(),hypertensionFollowDTO.getPicturePath3(), picture3);
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        //病人信息
        binding.editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString();
                if (idCard.length() >= 2 ){
                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
                    if (!CollectionUtils.isEmpty(dtoList)){
                        InhabitantDTO i = dtoList.get(0);
                        if (i != null){
                            inhabitantDTO = i;
//                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
//                                    @Override
//                                    public void onSuccess(Map result) {
//                                        String is = result.get("Msg").toString();
//                                        if ("1.0".equals(is)){
//                                            return;
//                                        }
//                                    }
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
//                                    }
//                                });
//                            }
                            setInhabitantView();
                        }else {
                            clearInhabitantView();
                        }
                    }else {
                        clearInhabitantView();
                        inhabitantDTO = null;
                    }
                }
            }
        });
        if (StringUtils.isNull(binding.textView626.getText().toString()))
            binding.textView626.setText(Utils.getTime(new Date()));
        //随访时间
        binding.textView626.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView626.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        if (StringUtils.isNull(binding.textView625.getText().toString()))
            binding.textView625.setText(Utils.getTime(new Date()));
        //下次随访时间
        binding.textView625.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView625.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("下次随访时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        //药物不良反应
        binding.radioGroupPlus30.setOnCheckedChangeListener(new RadioGroupPlus.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroupPlus group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButton495:
                        binding.editText208.setEnabled(false);
                        break;
                    case R.id.radioButton496:
                        binding.editText208.setEnabled(true);
                        break;
                }
            }
        });

        //设置症状的监听
        binding.radioButton95.setOnCheckedChangeListener(this);
        binding.radioButton96.setOnCheckedChangeListener(this);
        binding.radioButton97.setOnCheckedChangeListener(this);
        binding.radioButton98.setOnCheckedChangeListener(this);
        binding.radioButton99.setOnCheckedChangeListener(this);
        binding.radioButton100.setOnCheckedChangeListener(this);
        binding.radioButton102.setOnCheckedChangeListener(this);
        binding.radioButton106.setOnCheckedChangeListener(this);
        binding.radioButton107.setOnCheckedChangeListener(this);

        //设置常用药品的流式布局
        binding.imageView16.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                View view = View.inflate(getActivity(), R.layout.door_record_drug_add, null);
                alertDialog
                        .setView(view)
                        .create();
                final AlertDialog show = alertDialog.show();
                EditText name = view.findViewById(R.id.editText28);
                EditText dailyTimes = view.findViewById(R.id.editText32);
                EditText eachDose = view.findViewById(R.id.editText31);
                EditText company = view.findViewById(R.id.editText29);
                EditText remark = view.findViewById(R.id.editText65);
                RadioGroup usage = view.findViewById(R.id.radioGroup);
                Button save = view.findViewById(R.id.button21);
                Button cancel = view.findViewById(R.id.button20);
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtils.isNotNull(name.getText().toString())
                                && StringUtils.isNotNull(dailyTimes.getText().toString())
                                && StringUtils.isNotNull(eachDose.getText().toString())
                                && StringUtils.isNotNull(company.getText().toString())){
                            if ("mg".equals(company.getText().toString()) ||
                                    "ml".equals(company.getText().toString()) ||
                                    "g".equals(company.getText().toString()) ||
                                    "片".equals(company.getText().toString()) ||
                                    "粒".equals(company.getText().toString()) ||
                                    "袋".equals(company.getText().toString()) ||
                                    "瓶".equals(company.getText().toString()) ||
                                    "支".equals(company.getText().toString()) ||
                                    "盒".equals(company.getText().toString()) ||
                                    "U".equals(company.getText().toString())){
                                DrugVo followDrug = new DrugVo();
                                followDrug.setCmDrugName(name.getText().toString());
                                followDrug.setDailyTimes(dailyTimes.getText().toString());
                                followDrug.setEachDose(eachDose.getText().toString());
                                followDrug.setRemark(company.getText().toString());
                                followDrug.setRemark1(remark.getText().toString());
                                switch (usage.getCheckedRadioButtonId()){
                                    case R.id.radioButton44:
                                        followDrug.setCmDrugUsage("1");
                                        break;
                                    case R.id.radioButton46:
                                        followDrug.setCmDrugUsage("2");
                                        break;
                                    case R.id.radioButton47:
                                        followDrug.setCmDrugUsage("3");
                                        break;
                                }
                                drug.add(followDrug);
                                addFollowDrugAdapter.notifyDataSetChanged();
                                show.dismiss();
                            }else {
                                Utils.Toast(getActivity(),"单位必须填写mg,ml,g,片,粒,袋,瓶,支,盒,U中的一个！");
                            }
                        }else {
                            Utils.Toast(context,"不能为空！");
                        }
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        show.dismiss();
                    }
                });

            }
        });
        addFollowDrugAdapter = new AddFollowDrugAdapter(drug);
        addFollowDrugAdapter.setOnClickChangedData(new AddFollowDrugAdapter.ChangedData() {
            @Override
            public void changedData() {
                addFollowDrugAdapter.notifyDataSetChanged();
            }
        });

        binding.recycler.setLayoutManager(new LinearLayoutManager(context));
        binding.recycler.setAdapter(addFollowDrugAdapter);

        //设置添加或查看实验室检查
        binding.imageView14.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                View view = View.inflate(getActivity(), R.layout.exam_laboratory_layout, null);
                alertDialog
                        .setView(view)
                        .create();
                final AlertDialog show = alertDialog.show();
                show.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                show.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
                Spinner spinner = show.findViewById(R.id.spinner8);
                LinearLayout layout = show.findViewById(R.id.layout);
                Button save = view.findViewById(R.id.btn_right);
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        saveLaboratory(layout);
                        hypertensionFollowDTO.setLabora(GsonUtils.toJson(labora));
                        show.dismiss();
                    }

                    private void saveLaboratory(LinearLayout layout) {
                        List<View> allChildViews = getAllChildViews(layout);
                        for (View allChildView : allChildViews) {
                            if (allChildView instanceof EditText){
                                allChildView = (EditText)allChildView;
                                switch (allChildView.getId()){
                                    case R.id.BUltrasonicWave:
                                        labora.put("BUltrasonicWave",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.FecalOccultBlood:
                                        labora.put("FecalOccultBlood",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Ecg:
                                        labora.put("Ecg",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.GlycatedHemoglobin:
                                        labora.put("GlycatedHemoglobin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.HepatitisBSurfaceAntigen:
                                        labora.put("HepatitisBSurfaceAntigen",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.SerumAla:
                                        labora.put("SerumAla",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.SerumAa:
                                        labora.put("SerumAa",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Albumin:
                                        labora.put("Albumin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.TotalBilirubin:
                                        labora.put("TotalBilirubin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Bilirubin:
                                        labora.put("Bilirubin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.OtherLaboratory:
                                        labora.put("OtherLaboratory",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.SerumCreatinine:
                                        labora.put("SerumCreatinine",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Bun:
                                        labora.put("Bun",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.PotassiumConcentration:
                                        labora.put("PotassiumConcentration",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.SodiumConcentration:
                                        labora.put("SodiumConcentration",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Hemoglobin:
                                        labora.put("Hemoglobin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Leukocyte:
                                        labora.put("Leukocyte",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Platelet:
                                        labora.put("Platelet",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.OtherBlood:
                                        labora.put("OtherBlood",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.UrineProtein:
                                        labora.put("UrineProtein",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Urine:
                                        labora.put("Urine",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.Ketone:
                                        labora.put("Ketone",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.OccultBloodInUrine:
                                        labora.put("OccultBloodInUrine",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.OtherUrine:
                                        labora.put("OtherUrine",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.CervicalSmear:
                                        labora.put("CervicalSmear",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.UrinaryAlbumin:
                                        labora.put("UrinaryAlbumin",((EditText) allChildView).getText().toString());
                                        break;
                                    case R.id.ChestXRay:
                                        labora.put("ChestXRay",((EditText) allChildView).getText().toString());
                                        break;
                                }
                            }
                        }
                    }
                });
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,laboratoryString);
                spinner.setAdapter(arrayAdapter);
                overloadingLaboratory(layout,arrayAdapter,spinner);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        final String name = spinner.getItemAtPosition(position).toString();
                        switch (name){
                            case "血常规*":
                                setLaboratoryView(R.layout.laboratory_routine_blood_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "尿常规":
                                setLaboratoryView(R.layout.laboratory_routine_urine_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "心电图":
                                setLaboratoryView(R.layout.laboratory_electrocardiogram_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "尿微量白蛋白":
                                setLaboratoryView(R.layout.laboratory_urine_trace_albumin_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "大便潜血":
                                setLaboratoryView(R.layout.laboratory_defecate_occult_blood_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "乙型肝炎表面抗原":
                                setLaboratoryView(R.layout.laboratory_hepatitis_b_surface_antigen_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "肝功能*":
                                setLaboratoryView(R.layout.laboratory_liver_function_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "肾功能*":
                                setLaboratoryView(R.layout.laboratory_renal_function_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "胸部X线片":
                                setLaboratoryView(R.layout.laboratory_x_ray_of_the_chest_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "B超":
                                setLaboratoryView(R.layout.laboratory_b_mode_ultrasonography_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "宫颈涂片":
                                setLaboratoryView(R.layout.laboratory_the_cervical_smear_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "糖化血红蛋白":
                                setLaboratoryView(R.layout.laboratory_hba1c_item,name,arrayAdapter,layout,spinner);
                                break;
                            case "其他":
                                setLaboratoryView(R.layout.laboratory_other_item,name,arrayAdapter,layout,spinner);
                                break;
                        }
                    }



                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });

            }

            private void overloadingLaboratory(LinearLayout layout, ArrayAdapter<String> arrayAdapter, Spinner spinner) {

                if (labora.get("BUltrasonicWave") != null){
                    setLaboratoryView(R.layout.laboratory_b_mode_ultrasonography_item,"B超",arrayAdapter,layout,spinner);
                    EditText BUltrasonicWave = layout.findViewById(R.id.BUltrasonicWave);
                    BUltrasonicWave.setText(String.valueOf(labora.get("BUltrasonicWave")));
                }
                if (labora.get("FecalOccultBlood") != null){
                    setLaboratoryView(R.layout.laboratory_defecate_occult_blood_item,"大便潜血",arrayAdapter,layout,spinner);
                    EditText FecalOccultBlood = layout.findViewById(R.id.FecalOccultBlood);
                    FecalOccultBlood.setText(String.valueOf(labora.get("FecalOccultBlood")));
                }
                if (labora.get("Ecg") != null){
                    setLaboratoryView(R.layout.laboratory_electrocardiogram_item,"心电图",arrayAdapter,layout,spinner);
                    EditText Ecg = layout.findViewById(R.id.Ecg);
                    Ecg.setText(String.valueOf(labora.get("Ecg")));
                }
                if (labora.get("GlycatedHemoglobin") != null){
                    setLaboratoryView(R.layout.laboratory_hba1c_item,"糖化血红蛋白",arrayAdapter,layout,spinner);
                    EditText GlycatedHemoglobin = layout.findViewById(R.id.GlycatedHemoglobin);
                    GlycatedHemoglobin.setText(String.valueOf(labora.get("GlycatedHemoglobin")));
                }
                if (labora.get("HepatitisBSurfaceAntigen") != null){
                    setLaboratoryView(R.layout.laboratory_hepatitis_b_surface_antigen_item,"乙型肝炎表面抗原",arrayAdapter,layout,spinner);
                    EditText HepatitisBSurfaceAntigen = layout.findViewById(R.id.HepatitisBSurfaceAntigen);
                    HepatitisBSurfaceAntigen.setText(String.valueOf(labora.get("HepatitisBSurfaceAntigen")));
                }
                if (labora.get("SerumAla") != null
                        || labora.get("SerumAa") != null
                        || labora.get("Albumin") != null
                        || labora.get("TotalBilirubin") != null
                        || labora.get("Bilirubin") != null){
                    setLaboratoryView(R.layout.laboratory_liver_function_item,"肝功能*",arrayAdapter,layout,spinner);
                    EditText SerumAla = layout.findViewById(R.id.SerumAla);
                    SerumAla.setText(String.valueOf(labora.get("SerumAla")));
                    EditText SerumAa = layout.findViewById(R.id.SerumAa);
                    SerumAa.setText(String.valueOf(labora.get("SerumAa")));
                    EditText Albumin = layout.findViewById(R.id.Albumin);
                    Albumin.setText(String.valueOf(labora.get("Albumin")));
                    EditText TotalBilirubin = layout.findViewById(R.id.TotalBilirubin);
                    TotalBilirubin.setText(String.valueOf(labora.get("TotalBilirubin")));
                    EditText Bilirubin = layout.findViewById(R.id.Bilirubin);
                    Bilirubin.setText(String.valueOf(labora.get("Bilirubin")));
                }

                if (labora.get("OtherLaboratory") != null){
                    setLaboratoryView(R.layout.laboratory_other_item,"其他",arrayAdapter,layout,spinner);
                    EditText OtherLaboratory = layout.findViewById(R.id.OtherLaboratory);
                    OtherLaboratory.setText(String.valueOf(labora.get("OtherLaboratory")));
                }

                if (labora.get("SerumCreatinine") != null
                        || labora.get("Bun") != null
                        || labora.get("PotassiumConcentration") != null
                        || labora.get("SodiumConcentration") != null){
                    setLaboratoryView(R.layout.laboratory_renal_function_item,"肾功能*",arrayAdapter,layout,spinner);
                    EditText SerumCreatinine = layout.findViewById(R.id.SerumCreatinine);
                    SerumCreatinine.setText(String.valueOf(labora.get("SerumCreatinine")));
                    EditText Bun = layout.findViewById(R.id.Bun);
                    Bun.setText(String.valueOf(labora.get("Bun")));
                    EditText PotassiumConcentration = layout.findViewById(R.id.PotassiumConcentration);
                    PotassiumConcentration.setText(String.valueOf(labora.get("PotassiumConcentration")));
                    EditText SodiumConcentration = layout.findViewById(R.id.SodiumConcentration);
                    SodiumConcentration.setText(String.valueOf(labora.get("SodiumConcentration")));
                }

                if (labora.get("Hemoglobin") != null
                        || labora.get("Leukocyte") != null
                        || labora.get("Platelet") != null
                        || labora.get("OtherBlood") != null){
                    setLaboratoryView(R.layout.laboratory_routine_blood_item,"血常规*",arrayAdapter,layout,spinner);
                    EditText Hemoglobin = layout.findViewById(R.id.Hemoglobin);
                    Hemoglobin.setText(String.valueOf(labora.get("Hemoglobin")));
                    EditText Leukocyte = layout.findViewById(R.id.Leukocyte);
                    Leukocyte.setText(String.valueOf(labora.get("Leukocyte")));
                    EditText Platelet = layout.findViewById(R.id.Platelet);
                    Platelet.setText(String.valueOf(labora.get("Platelet")));
                    EditText OtherBlood = layout.findViewById(R.id.OtherBlood);
                    OtherBlood.setText(String.valueOf(labora.get("OtherBlood")));
                }

                if (labora.get("UrineProtein") != null
                        || labora.get("Urine") != null
                        || labora.get("Ketone") != null
                        || labora.get("OccultBloodInUrine") != null
                        || labora.get("OtherUrine") != null){
                    setLaboratoryView(R.layout.laboratory_routine_urine_item,"尿常规",arrayAdapter,layout,spinner);
                    EditText UrineProtein = layout.findViewById(R.id.UrineProtein);
                    UrineProtein.setText(String.valueOf(labora.get("UrineProtein")));
                    EditText Urine = layout.findViewById(R.id.Urine);
                    Urine.setText(String.valueOf(labora.get("Urine")));
                    EditText Ketone = layout.findViewById(R.id.Ketone);
                    Ketone.setText(String.valueOf(labora.get("Ketone")));
                    EditText OccultBloodInUrine = layout.findViewById(R.id.OccultBloodInUrine);
                    OccultBloodInUrine.setText(String.valueOf(labora.get("OccultBloodInUrine")));
                    EditText OtherUrine = layout.findViewById(R.id.OtherUrine);
                    OtherUrine.setText(String.valueOf(labora.get("OtherUrine")));
                }

                if (labora.get("CervicalSmear") != null){
                    setLaboratoryView(R.layout.laboratory_the_cervical_smear_item,"宫颈涂片",arrayAdapter,layout,spinner);
                    EditText CervicalSmear = layout.findViewById(R.id.CervicalSmear);
                    CervicalSmear.setText(String.valueOf(labora.get("CervicalSmear")));
                }

                if (labora.get("UrinaryAlbumin") != null){
                    setLaboratoryView(R.layout.laboratory_urine_trace_albumin_item,"尿微量白蛋白",arrayAdapter,layout,spinner);
                    EditText UrinaryAlbumin = layout.findViewById(R.id.UrinaryAlbumin);
                    UrinaryAlbumin.setText(String.valueOf(labora.get("UrinaryAlbumin")));
                }

                if (labora.get("ChestXRay") != null){
                    setLaboratoryView(R.layout.laboratory_x_ray_of_the_chest_item,"胸部X线片",arrayAdapter,layout,spinner);
                    EditText ChestXRay = layout.findViewById(R.id.ChestXRay);
                    ChestXRay.setText(String.valueOf(labora.get("ChestXRay")));
                }


            }
            private void setLaboratoryView(int id, String name, ArrayAdapter<String> arrayAdapter,
                                           LinearLayout layout, Spinner spinner) {
                View item = View.inflate(getActivity(),id, null);
                TextView delete = item.findViewById(R.id.delete);
                arrayAdapter.remove(name);
                switch (id){
                    case R.layout.laboratory_b_mode_ultrasonography_item:
                        if (StringUtils.isNull(labora.get("BUltrasonicWave")))
                            labora.put("BUltrasonicWave","");
                        break;
                    case R.layout.laboratory_defecate_occult_blood_item:
                        if (StringUtils.isNull(labora.get("FecalOccultBlood")))
                            labora.put("FecalOccultBlood","");
                        break;
                    case R.layout.laboratory_electrocardiogram_item:
                        if (StringUtils.isNull(labora.get("Ecg")))
                            labora.put("Ecg","");
                        break;
                    case R.layout.laboratory_hba1c_item:
                        if (StringUtils.isNull(labora.get("GlycatedHemoglobin")))
                            labora.put("GlycatedHemoglobin","");
                        break;
                    case R.layout.laboratory_hepatitis_b_surface_antigen_item:
                        if (StringUtils.isNull(labora.get("HepatitisBSurfaceAntigen")))
                            labora.put("HepatitisBSurfaceAntigen","");
                        break;
                    case R.layout.laboratory_liver_function_item:
                        if (StringUtils.isNull(labora.get("SerumAla")))
                            labora.put("SerumAla","");
                        if (StringUtils.isNull(labora.get("SerumAa")))
                            labora.put("SerumAa","");
                        if (StringUtils.isNull(labora.get("Albumin")))
                            labora.put("Albumin","");
                        if (StringUtils.isNull(labora.get("TotalBilirubin")))
                            labora.put("TotalBilirubin","");
                        if (StringUtils.isNull(labora.get("Bilirubin")))
                            labora.put("Bilirubin","");
                        break;
                    case R.layout.laboratory_other_item:
                        if (StringUtils.isNull(labora.get("OtherLaboratory")))
                            labora.put("OtherLaboratory","");
                        break;
                    case R.layout.laboratory_renal_function_item:
                        if (StringUtils.isNull(labora.get("SerumCreatinine")))
                            labora.put("SerumCreatinine","");
                        if (StringUtils.isNull(labora.get("Bun")))
                            labora.put("Bun","");
                        if (StringUtils.isNull(labora.get("PotassiumConcentration")))
                            labora.put("PotassiumConcentration","");
                        if (StringUtils.isNull(labora.get("SodiumConcentration")))
                            labora.put("SodiumConcentration","");
                        break;
                    case R.layout.laboratory_routine_blood_item:
                        if (StringUtils.isNull(labora.get("Hemoglobin")))
                            labora.put("Hemoglobin","");
                        if (StringUtils.isNull(labora.get("Leukocyte")))
                            labora.put("Leukocyte","");
                        if (StringUtils.isNull(labora.get("Platelet")))
                            labora.put("Platelet","");
                        if (StringUtils.isNull(labora.get("OtherBlood")))
                            labora.put("OtherBlood","");
                        break;
                    case R.layout.laboratory_routine_urine_item:
                        if (StringUtils.isNull(labora.get("UrineProtein")))
                            labora.put("UrineProtein","");
                        if (StringUtils.isNull(labora.get("Urine")))
                            labora.put("Urine","");
                        if (StringUtils.isNull(labora.get("Ketone")))
                            labora.put("Ketone","");
                        if (StringUtils.isNull(labora.get("OccultBloodInUrine")))
                            labora.put("OccultBloodInUrine","");
                        if (StringUtils.isNull(labora.get("OtherUrine")))
                            labora.put("OtherUrine","");
                        break;
                    case R.layout.laboratory_the_cervical_smear_item:
                        if (StringUtils.isNull(labora.get("CervicalSmear")))
                            labora.put("CervicalSmear","");
                        break;
                    case R.layout.laboratory_urine_trace_albumin_item:
                        if (StringUtils.isNull(labora.get("UrinaryAlbumin")))
                            labora.put("UrinaryAlbumin","");
                        break;
                    case R.layout.laboratory_x_ray_of_the_chest_item:
                        if (StringUtils.isNull(labora.get("ChestXRay")))
                            labora.put("ChestXRay","");
                        break;
                }
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        layout.removeView(item);
                        switch (id){
                            case R.layout.laboratory_b_mode_ultrasonography_item:
                                if (labora.get("BUltrasonicWave") != null)
                                    labora.remove("BUltrasonicWave");
                                break;
                            case R.layout.laboratory_defecate_occult_blood_item:
                                if (labora.get("FecalOccultBlood") != null)
                                    labora.remove("FecalOccultBlood");
                                break;
                            case R.layout.laboratory_electrocardiogram_item:
                                if (labora.get("Ecg") != null)
                                    labora.remove("Ecg");
                                break;
                            case R.layout.laboratory_hba1c_item:
                                if (labora.get("GlycatedHemoglobin") != null)
                                    labora.remove("GlycatedHemoglobin");
                                break;
                            case R.layout.laboratory_hepatitis_b_surface_antigen_item:
                                if (labora.get("HepatitisBSurfaceAntigen") != null)
                                    labora.remove("HepatitisBSurfaceAntigen");
                                break;
                            case R.layout.laboratory_liver_function_item:
                                if (labora.get("SerumAla") != null)
                                    labora.remove("SerumAla");
                                if (labora.get("SerumAa") != null)
                                    labora.remove("SerumAa");
                                if (labora.get("Albumin") != null)
                                    labora.remove("Albumin");
                                if (labora.get("TotalBilirubin") != null)
                                    labora.remove("TotalBilirubin");
                                if (labora.get("Bilirubin") != null)
                                    labora.remove("Bilirubin");
                                break;
                            case R.layout.laboratory_other_item:
                                if (labora.get("OtherLaboratory") != null)
                                    labora.remove("OtherLaboratory");
                                break;
                            case R.layout.laboratory_renal_function_item:
                                if (labora.get("SerumCreatinine") != null)
                                    labora.remove("SerumCreatinine");
                                if (labora.get("Bun") != null)
                                    labora.remove("Bun");
                                if (labora.get("PotassiumConcentration") != null)
                                    labora.remove("PotassiumConcentration");
                                if (labora.get("SodiumConcentration") != null)
                                    labora.remove("SodiumConcentration");
                                break;
                            case R.layout.laboratory_routine_blood_item:
                                if (labora.get("Hemoglobin") != null)
                                    labora.remove("Hemoglobin");
                                if (labora.get("Leukocyte") != null)
                                    labora.remove("Leukocyte");
                                if (labora.get("Platelet") != null)
                                    labora.remove("Platelet");
                                if (labora.get("OtherBlood") != null)
                                    labora.remove("OtherBlood");
                                break;
                            case R.layout.laboratory_routine_urine_item:
                                if (labora.get("UrineProtein") != null)
                                    labora.remove("UrineProtein");
                                if (labora.get("Urine") != null)
                                    labora.remove("Urine");
                                if (labora.get("Ketone") != null)
                                    labora.remove("Ketone");
                                if (labora.get("OccultBloodInUrine") != null)
                                    labora.remove("OccultBloodInUrine");
                                if (labora.get("OtherUrine") != null)
                                    labora.remove("OtherUrine");
                                break;
                            case R.layout.laboratory_the_cervical_smear_item:
                                if (labora.get("CervicalSmear") != null)
                                    labora.remove("CervicalSmear");
                                break;
                            case R.layout.laboratory_urine_trace_albumin_item:
                                if (labora.get("UrinaryAlbumin") != null)
                                    labora.remove("UrinaryAlbumin");
                                break;
                            case R.layout.laboratory_x_ray_of_the_chest_item:
                                if (labora.get("ChestXRay") != null)
                                    labora.remove("ChestXRay");
                                break;
                        }
                        arrayAdapter.add(name);
                    }
                });
                layout.addView(item);
                spinner.setSelection(0);
            }
        });

        //返回
        binding.button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideAddFragment();
            }
        });

        //保存
        binding.button46.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inhabitantDTO == null){
                    Utils.Toast(context,"请完善病人信息！");
                    return;
                }
                hypertensionFollowDTO.setAddress(address.getText().toString());
                if (StringUtils.isNull(hypertensionFollowDTO.getAddress())
                        || (StringUtils.isNull(hypertensionFollowDTO.getPicturePath1())
                        && StringUtils.isNull(hypertensionFollowDTO.getPicturePath2())
                        && StringUtils.isNull(hypertensionFollowDTO.getPicturePath3()))){
                    Utils.Toast(context,"请完善地址信息或者拍摄现场图片后再保存！");
                    return;
                }
                save();
                hypertensionFollowDTO.setPersonID(inhabitantDTO.getID());
                hypertensionFollowDTO.setPersonName(inhabitantDTO.getNAME());
                if (StringUtils.isNull(hypertensionFollowDTO.getID()))
                    hypertensionFollowDTO.setID(UUID.randomUUID().toString());
                viewModel.getHypertensionFollowRepository().insert(hypertensionFollowDTO);
                Utils.Toast(context,"保存本地成功！");
                hideAddFragment();
//                if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                    String oldId = hypertensionFollowDTO.getID();
//                    if (hypertensionFollowDTO.getID() != null && hypertensionFollowDTO.getID().endsWith("@"))
//                        hypertensionFollowDTO.setID(null);
//                    HypertensionInterface.saveOrUpdateHypertensionFollow(hypertensionFollowDTO, viewModel.getUserInfo().getLoginVo().getOrgId(), new WebServiceUtils.Response<Map>() {
//                        @Override
//                        public void onSuccess(Map result) {
//                            if (result.get("ID") != null){
//                                String id = result.get("ID").toString();
//                                if (hypertensionFollowDTO.getID() == null){
//                                    if (StringUtils.isNotNull(oldId)){
//                                        hypertensionFollowDTO.setID(oldId);
//                                        viewModel.getHypertensionFollowRepository().delete(hypertensionFollowDTO);
//                                    }
//                                    hypertensionFollowDTO.setID(id);
//                                    viewModel.getHypertensionFollowRepository().insert(hypertensionFollowDTO);
//                                }
//                                Utils.Toast(context,"保存成功！");
//                            }else {
//                                viewModel.getHypertensionFollowRepository().insert(hypertensionFollowDTO);
//                                Utils.Toast(context,"修改成功！");
//                            }
//                            hideAddFragment();
//                        }
//
//                        @Override
//                        public void onError(String error) {
//                            Utils.Toast(context,"保存失败！\n失败原因：" + error);
//                        }
//                    });
//
//                }else {
//                    if (StringUtils.isNull(hypertensionFollowDTO.getID()))
//                        hypertensionFollowDTO.setID(UUID.randomUUID().toString() + "@");
//                    viewModel.getHypertensionFollowRepository().insert(hypertensionFollowDTO);
//                    Utils.Toast(context,"保存本地成功！");
//                    hideAddFragment();
//                }
            }
        });


    }

    /**
     * 初始化数据
     */
    private void initData() {
        laboratoryString = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.exam_laboratory_adapter)));
        Bundle arguments = getArguments();

        if (arguments == null){
            hypertensionFollowDTO = new HypertensionFollowDTO();
            labora = new LinkedHashMap<>();
            drug = new ArrayList<>();
            other = new ArrayList<>();
        }
        else {
            hypertensionFollowDTO = (HypertensionFollowDTO) arguments.get("hypertensionFollowDTO");
            labora = GsonUtils.fromJson(hypertensionFollowDTO.getLabora(),Map.class);
            drug = GsonUtils.jsonToList(hypertensionFollowDTO.getDrug(),DrugVo.class);
            other = GsonUtils.fromJson(hypertensionFollowDTO.getOther(),List.class);
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID",hypertensionFollowDTO.getPersonID());
            if (inhabitantDTO == null){
                Utils.Toast(context,"请先更新病人数据！");
                hideAddFragment();
                return;
            }
            echo();
        }
    }

    /**
     * 回显数据
     */
    private void echo() {
        setInhabitantView();
        //随访方式
        if(StringUtils.isNotNull(hypertensionFollowDTO.getWayUp())){
            switch (hypertensionFollowDTO.getWayUp()){
                case "1":
                    binding.radioGroupPlus021.check(R.id.radioButton240);
                    break;
                case "2":
                    binding.radioGroupPlus021.check(R.id.radioButton241);
                    break;
                case "4":
                    binding.radioGroupPlus021.check(R.id.radioButton242);
                    break;
                case "8":
                    binding.radioGroupPlus021.check(R.id.radioButton2433);
                    break;
            }
        }

        //症状
        if (StringUtils.isNotNull(hypertensionFollowDTO.getSymptom())
                && !hypertensionFollowDTO.getSymptom().equals("0")){
            List<Integer> list = Utils.divisionBinary(Integer.valueOf(hypertensionFollowDTO.getSymptom()));
            for (Integer integer : list) {
                switch (integer){
                    case 1:
                        binding.radioButton95.setChecked(true);
                        binding.editTextTextPersonName96.setEnabled(false);
                        break;
                    case 2:
                        binding.radioButton96.setChecked(true);
                        break;
                    case 3:
                        binding.radioButton97.setChecked(true);
                        break;
                    case 4:
                        binding.radioButton98.setChecked(true);
                        break;
                    case 5:
                        binding.radioButton99.setChecked(true);
                        break;
                    case 6:
                        binding.radioButton100.setChecked(true);
                        break;
                    case 7:
                        binding.radioButton102.setChecked(true);
                        break;
                    case 8:
                        binding.radioButton106.setChecked(true);
                        break;
                    case 9:
                        binding.radioButton107.setChecked(true);
                        break;
                    case 18:
                        if (getMap("Symptom") != null){
                            String symptom = getMap("Symptom");
                            binding.editTextTextPersonName96.setEnabled(true);
                            binding.editTextTextPersonName96.setText(symptom);
                        }
                        break;
                }
            }
        }

        //下次随访日期
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextFollowUpDate()))
            binding.textView625.setText(hypertensionFollowDTO.getNextFollowUpDate());

        //体征其他
        if(StringUtils.isNotNull(hypertensionFollowDTO.getExamBodyOther()))
            binding.editTextTextPersonName28.setText(hypertensionFollowDTO.getExamBodyOther());

        //下次目标体重
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextWeight()))
            binding.editTextTextPersonName99.setText(hypertensionFollowDTO.getNextWeight());

        //下次目标心率
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextHeartRate()))
            binding.editTextTextPersonName55.setText(hypertensionFollowDTO.getNextHeartRate());

        //下次目标日吸烟量
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextSmoking()))
            binding.editTextTextPersonName102.setText(hypertensionFollowDTO.getNextSmoking());

        //下次目标日饮酒量
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextDailyAlcohol()))
            binding.editTextTextPersonName103.setText(hypertensionFollowDTO.getNextDailyAlcohol());

        //摄盐情况 咸淡（1 轻 2 中 4重)，默认为0
        if (StringUtils.isNotNull(hypertensionFollowDTO.getSaltIntake())){
            switch (hypertensionFollowDTO.getSaltIntake()){
                case "1":
                    binding.radioGroupPlus04.check(R.id.radioButton247);
                    break;
                case "2":
                    binding.radioGroupPlus04.check(R.id.radioButton248);
                    break;
                case "4":
                    binding.radioGroupPlus04.check(R.id.radioButton249);
                    break;
            }
        }

        //下次锻炼每周次数
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextExerciseWeekTimes()))
            binding.editTextTextPersonName105.setText(hypertensionFollowDTO.getNextExerciseWeekTimes());

        //下次锻炼周次分钟
        if(StringUtils.isNotNull(hypertensionFollowDTO.getNextExerciseWeekMinute()))
            binding.editTextTextPersonName104.setText(hypertensionFollowDTO.getNextExerciseWeekMinute());

        //心里调整number：1 良好 2 一般 4 差
        if (StringUtils.isNotNull(hypertensionFollowDTO.getPsychologicalAdjustment())){
            switch (hypertensionFollowDTO.getPsychologicalAdjustment()){
                case "1":
                    binding.radioGroupPlus05.check(R.id.radioButton250);
                    break;
                case "2":
                    binding.radioGroupPlus05.check(R.id.radioButton251);
                    break;
                case "4":
                    binding.radioGroupPlus05.check(R.id.radioButton252);
                    break;
            }
        }

        //遵医行为number：1 良好 2 一般 4 差
        if (StringUtils.isNotNull(hypertensionFollowDTO.getComplianceBehavior())){
            switch (hypertensionFollowDTO.getComplianceBehavior()){
                case "1":
                    binding.radioGroupPlus06.check(R.id.radioButton253);
                    break;
                case "2":
                    binding.radioGroupPlus06.check(R.id.radioButton254);
                    break;
                case "4":
                    binding.radioGroupPlus06.check(R.id.radioButton255);
                    break;
            }
        }

        //服药依从性number：1 规律 2 间断 4 不服药
        if (StringUtils.isNotNull(hypertensionFollowDTO.getMedicationCompliance())){
            switch (hypertensionFollowDTO.getMedicationCompliance()){
                case "1":
                    binding.radioGroupPlus061.check(R.id.radioButton2531);
                    break;
                case "2":
                    binding.radioGroupPlus061.check(R.id.radioButton2541);
                    break;
                case "4":
                    binding.radioGroupPlus061.check(R.id.radioButton2551);
                    break;
            }
        }

        //药物不良反应varchar “1”无 “2”有（内容放otherjson里面）
        if (StringUtils.isNotNull(hypertensionFollowDTO.getAdverseDrugReactions())){
            switch (hypertensionFollowDTO.getAdverseDrugReactions()){
                case "1":
                    binding.radioGroupPlus30.check(R.id.radioButton495);
                    break;
                case "2":
                    binding.radioGroupPlus30.check(R.id.radioButton496);
                    if (getMap("AdverseDrugReactions") != null)
                        binding.editText208.setText(getMap("AdverseDrugReactions"));
                    break;
            }
        }

        //此次随访分类Integer：1 控制满意 2 控制不满意 4 不良反应 8 并发症
        if(StringUtils.isNotNull(hypertensionFollowDTO.getFuClassification())){
            switch (hypertensionFollowDTO.getFuClassification()){
                case "1":
                    binding.radioGroupPlus07.check(R.id.radioButton258);
                    break;
                case "2":
                    binding.radioGroupPlus07.check(R.id.radioButton259);
                    break;
                case "4":
                    binding.radioGroupPlus07.check(R.id.radioButton256);
                    break;
                case "8":
                    binding.radioGroupPlus07.check(R.id.radioButton257);
                    break;
            }
        }

        //随访结局
        if(StringUtils.isNotNull(hypertensionFollowDTO.getFollowUpRemarks()))
            binding.textView278.setText(hypertensionFollowDTO.getFollowUpRemarks());

        //随访日期
        if(StringUtils.isNotNull(hypertensionFollowDTO.getFollowUpDate()))
            binding.textView626.setText(hypertensionFollowDTO.getFollowUpDate());

        //随访医生
        if(StringUtils.isNotNull(hypertensionFollowDTO.getDoctorName()))
            binding.editTextTextPersonName111.setText(hypertensionFollowDTO.getDoctorName());

        //健康指导
        if(StringUtils.isNotNull(hypertensionFollowDTO.getHealthGuidance()))
            binding.textView281.setText(hypertensionFollowDTO.getHealthGuidance());

        //心率
        if(StringUtils.isNotNull(hypertensionFollowDTO.getHeartRate()))
            binding.editTextTextPersonName55.setText(hypertensionFollowDTO.getHeartRate());

        //右侧收缩压
        if(StringUtils.isNotNull(hypertensionFollowDTO.getRightSbp()))
            binding.editTextTextPersonName98.setText(hypertensionFollowDTO.getRightSbp());

        //右侧舒张压
        if(StringUtils.isNotNull(hypertensionFollowDTO.getRightDbp()))
            binding.editTextTextPersonName97.setText(hypertensionFollowDTO.getRightDbp());

        //身高
        if(StringUtils.isNotNull(hypertensionFollowDTO.getHeight()))
            binding.editTextTextPersonName101.setText(hypertensionFollowDTO.getHeight());

        //体重
        if(StringUtils.isNotNull(hypertensionFollowDTO.getWeight()))
            binding.editTextTextPersonName.setText(hypertensionFollowDTO.getWeight());

        //体质指数
        if(StringUtils.isNotNull(hypertensionFollowDTO.getBmi()))
            binding.editTextTextPersonName100.setText(hypertensionFollowDTO.getBmi());

        //每次锻炼时间
        if(StringUtils.isNotNull(hypertensionFollowDTO.getEachExerciseTime()))
            binding.editTextTextPersonName66.setText(hypertensionFollowDTO.getEachExerciseTime());

        //每周锻炼次数
        if(StringUtils.isNotNull(hypertensionFollowDTO.getExerciseWeekTimes()))
            binding.editTextTextPersonName67.setText(hypertensionFollowDTO.getExerciseWeekTimes());

        //日吸烟量
        if(StringUtils.isNotNull(hypertensionFollowDTO.getSmoking()))
            binding.editTextTextPersonName56.setText(hypertensionFollowDTO.getSmoking());

        //日饮酒量
        if(StringUtils.isNotNull(hypertensionFollowDTO.getDailyAlcoholIntake()))
            binding.editTextTextPersonName57.setText(hypertensionFollowDTO.getDailyAlcoholIntake());

        //机构及级别
        if(StringUtils.isNotNull(hypertensionFollowDTO.getTargetOrgName()))
            binding.editTextTextPersonName577.setText(hypertensionFollowDTO.getTargetOrgName());

        //原因
        if(StringUtils.isNotNull(hypertensionFollowDTO.getTranoutReasons()))
            binding.editTextTextPersonName110.setText(hypertensionFollowDTO.getTranoutReasons());

    }

    /**
     * 保存数据
     */
    private void save(){
        //下次随访日期
        hypertensionFollowDTO.setNextFollowUpDate(binding.textView625.getText().toString());

        //随访方式(1 门诊 2 家庭 4 电话  8其他)
        int checkedRadioButtonId = binding.radioGroupPlus021.getCheckedRadioButtonId();
        String wayUp = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton240:
                wayUp = "1";
                break;
            case R.id.radioButton241:
                wayUp = "2";
                break;
            case R.id.radioButton242:
                wayUp = "4";
                break;
            case R.id.radioButton2433:
                wayUp = "8";
                break;
        }
        hypertensionFollowDTO.setWayUp(wayUp);

        //症状(1 无症状(选1就不能选择其它选项) 2 头痛头晕 4 恶心呕吐 8 眼花耳鸣 16 呼吸困难 32 心悸胸闷 64 鼻衄 128 四肢发麻 256 下肢水肿 131072 其他（内容放otherjson里）)<必填>
        hypertensionFollowDTO.setSymptom(totalSymptom());

        //体征其他
        hypertensionFollowDTO.setExamBodyOther(binding.editTextTextPersonName28.getText().toString());

        //下次目标体重
        hypertensionFollowDTO.setNextWeight(binding.editTextTextPersonName99.getText().toString());

        //下次目标心率
        hypertensionFollowDTO.setNextHeartRate(binding.editTextTextPersonName55.getText().toString());

        //下次目标日吸烟量
        hypertensionFollowDTO.setNextSmoking(binding.editTextTextPersonName102.getText().toString());

        //下次目标日饮酒量
        hypertensionFollowDTO.setNextDailyAlcohol(binding.editTextTextPersonName103.getText().toString());

        //摄盐情况 咸淡（1 轻 2 中 4重)，默认为0
        checkedRadioButtonId = binding.radioGroupPlus04.getCheckedRadioButtonId();
        String saltIntake = "0";
        switch (checkedRadioButtonId){
            case R.id.radioButton247:
                saltIntake = "1";
                break;
            case R.id.radioButton248:
                saltIntake = "2";
                break;
            case R.id.radioButton249:
                saltIntake = "4";
                break;
        }
        hypertensionFollowDTO.setSaltIntake(saltIntake);
        hypertensionFollowDTO.setNextSaltIntake(saltIntake);

        //下次锻炼每周次数
        hypertensionFollowDTO.setNextExerciseWeekTimes(binding.editTextTextPersonName105.getText().toString());

        //下次锻炼周次分钟
        hypertensionFollowDTO.setNextExerciseWeekMinute(binding.editTextTextPersonName104.getText().toString());

        //心里调整number：1 良好 2 一般 4 差
        checkedRadioButtonId = binding.radioGroupPlus05.getCheckedRadioButtonId();
        String psychologicalAdjustment = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton250:
                psychologicalAdjustment = "1";
                break;
            case R.id.radioButton251:
                psychologicalAdjustment = "2";
                break;
            case R.id.radioButton252:
                psychologicalAdjustment = "4";
                break;
        }
        hypertensionFollowDTO.setPsychologicalAdjustment(psychologicalAdjustment);

        //遵医行为number：1 良好 2 一般 4 差
        checkedRadioButtonId = binding.radioGroupPlus06.getCheckedRadioButtonId();
        String complianceBehavior = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton253:
                complianceBehavior = "1";
                break;
            case R.id.radioButton254:
                complianceBehavior = "2";
                break;
            case R.id.radioButton255:
                complianceBehavior = "4";
                break;
        }
        hypertensionFollowDTO.setComplianceBehavior(complianceBehavior);

        //服药依从性number：1 规律 2 间断 4 不服药
        checkedRadioButtonId = binding.radioGroupPlus061.getCheckedRadioButtonId();
        String medicationCompliance = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton2531:
                medicationCompliance = "1";
                break;
            case R.id.radioButton2541:
                medicationCompliance = "2";
                break;
            case R.id.radioButton2551:
                medicationCompliance = "4";
                break;
        }
        hypertensionFollowDTO.setMedicationCompliance(medicationCompliance);

        //药物不良反应varchar “1”无 “2”有（内容放otherjson里面）
        checkedRadioButtonId = binding.radioGroupPlus30.getCheckedRadioButtonId();
        String adverseDrugReactions = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton495:
                adverseDrugReactions = "1";
                break;
            case R.id.radioButton496:
                adverseDrugReactions = "2";
                if (StringUtils.isNotNull(binding.editText208.getText().toString()))
                    setMap("AdverseDrugReactions",binding.editText208.getText().toString());
                break;
        }
        hypertensionFollowDTO.setAdverseDrugReactions(adverseDrugReactions);

        //此次随访分类Integer：1 控制满意 2 控制不满意 4 不良反应 8 并发症
        checkedRadioButtonId = binding.radioGroupPlus07.getCheckedRadioButtonId();
        String fuClassification = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton258:
                fuClassification = "1";
                break;
            case R.id.radioButton259:
                fuClassification = "2";
                break;
            case R.id.radioButton256:
                fuClassification = "4";
                break;
            case R.id.radioButton257:
                fuClassification = "8";
                break;
        }
        hypertensionFollowDTO.setFuClassification(fuClassification);

        //随访结局
        hypertensionFollowDTO.setFollowUpRemarks(binding.textView278.getText().toString());

        //随访日期
        hypertensionFollowDTO.setFollowUpDate(binding.textView626.getText().toString());

        //随访医生
        hypertensionFollowDTO.setDoctorID(viewModel.getUserInfo().getDId());
        hypertensionFollowDTO.setDoctorName(viewModel.getUserInfo().getDoctorName());

        //操作用户id
        hypertensionFollowDTO.setUserID(viewModel.getUserInfo().getDId());

        //健康指导
        hypertensionFollowDTO.setHealthGuidance(binding.textView281.getText().toString());

        //心率
        hypertensionFollowDTO.setHeartRate(binding.editTextTextPersonName55.getText().toString());

        //右侧收缩压
        hypertensionFollowDTO.setRightSbp(binding.editTextTextPersonName98.getText().toString());

        //右侧舒张压
        hypertensionFollowDTO.setRightDbp(binding.editTextTextPersonName97.getText().toString());

        //身高
        hypertensionFollowDTO.setHeight(binding.editTextTextPersonName101.getText().toString());

        //体重
        hypertensionFollowDTO.setWeight(binding.editTextTextPersonName.getText().toString());

        //体质指数
        hypertensionFollowDTO.setBmi(binding.editTextTextPersonName100.getText().toString());

        //每次锻炼时间
        hypertensionFollowDTO.setEachExerciseTime(binding.editTextTextPersonName66.getText().toString());

        //每周锻炼次数
        hypertensionFollowDTO.setExerciseWeekTimes(binding.editTextTextPersonName67.getText().toString());

        //日吸烟量
        hypertensionFollowDTO.setSmoking(binding.editTextTextPersonName56.getText().toString());

        //日饮酒量
        hypertensionFollowDTO.setDailyAlcoholIntake(binding.editTextTextPersonName57.getText().toString());

        //机构及级别
        hypertensionFollowDTO.setTargetOrgName(binding.editTextTextPersonName577.getText().toString());

        //原因
        hypertensionFollowDTO.setTranoutReasons(binding.editTextTextPersonName110.getText().toString());

        //其他
        hypertensionFollowDTO.setOther(GsonUtils.toJson(other));

        //常用药品
        hypertensionFollowDTO.setDrug(GsonUtils.toJson(drug));

        //实验室检查
        hypertensionFollowDTO.setLabora(GsonUtils.toJson(labora));


    }

    /**
     * 设置other值
     * @param key
     * @param value
     */
    private void setMap(String key, String value) {
        Map<String,Map> keys = new HashMap<>();
        for (Map<String, Object> map : other) {
            String k = map.get("AttrName").toString();
            keys.put(k,map);
        }
        if (keys.keySet().contains(key)){
            Map map = keys.get(key);
            map.put("OtherText",value);
        }else {
            Map map = new HashMap();
            map.put("AttrName",key);
            map.put("OtherText",value);
            other.add(map);
        }
    }

    /**
     * 隐藏Fragment
     */
    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }

    private void setInhabitantView(){
        binding.textView177.setText(inhabitantDTO.getNAME());
        if ("1".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("男");
        else if ("2".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("女");
        binding.textView183.setText(inhabitantDTO.getTEL());
        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){
        binding.textView177.setText("");
        binding.textView179.setText("");
        binding.textView183.setText("");
        binding.textView184.setText("");
        Utils.Toast(context,"未查到该身份证的信息，请同步居民信息后再添加！");
    }

    public String getMap(String str){
        for (Map<String, Object> map : other) {
            String attrName = map.get("AttrName").toString();
            String otherText = map.get("OtherText").toString();
            if (attrName.equals(str))
                return otherText;
        }
        return null;
    }

    private List<View> getAllChildViews(View view) {
        List<View> allchildren = new ArrayList<View>();
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                allchildren.add(viewchild);
                allchildren.addAll(getAllChildViews(viewchild));
            }
        }
        return allchildren;
    }

    /**
     * 计算症状总值
     * @return
     */
    private String totalSymptom() {
        int symptom = 0;
        if (binding.radioButton95.isChecked())
            return "1";
        if (binding.radioButton96.isChecked())
            symptom+=2;
        if (binding.radioButton97.isChecked())
            symptom+=4;
        if (binding.radioButton98.isChecked())
            symptom+=8;
        if (binding.radioButton99.isChecked())
            symptom+=16;
        if (binding.radioButton100.isChecked())
            symptom+=32;
        if (binding.radioButton102.isChecked())
            symptom+=64;
        if (binding.radioButton106.isChecked())
            symptom+=128;
        if (binding.radioButton107.isChecked())
            symptom+=256;
        if (StringUtils.isNotNull(binding.editTextTextPersonName96.getText().toString())){
            symptom+=131072;
            setMap("Symptom",binding.editTextTextPersonName96.getText().toString());
        }
        return String.valueOf(symptom);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == binding.radioButton95.getId()){
            if (isChecked){
                binding.editTextTextPersonName96.setEnabled(false);
            }else {
                binding.editTextTextPersonName96.setEnabled(true);
            }
        }
        if (binding.radioButton95.isChecked() && buttonView.getId() != binding.radioButton95.getId()){
            Utils.Toast(context,"请先取消没有症状选项！");
            buttonView.setChecked(false);
            return;
        }
        if (binding.radioButton96.isChecked()
                || binding.radioButton97.isChecked()
                || binding.radioButton98.isChecked()
                || binding.radioButton99.isChecked()
                || binding.radioButton100.isChecked()
                || binding.radioButton102.isChecked()
                || binding.radioButton106.isChecked()
                || binding.radioButton107.isChecked()){
            if (buttonView.getId() == binding.radioButton95.getId()){
                Utils.Toast(context,"请先取消其他选项！");
                buttonView.setChecked(false);
                return;
            }
        }
    }
}
